/**
 * 
 */
package calculation.passed;

/**
 * @author xyyi
 *
 */
public class AddBinary {

	/**
	Given two binary strings, return their sum (also a binary string).

	For example,
	a = "11"
	b = "1"
	Return "100".
	 */
	public String addBinary(String a, String b) {
		if (a.isEmpty() && b.isEmpty())
			return "";
		if (a.isEmpty())
			return b;
		if (b.isEmpty())
			return a;

		StringBuffer sb = new StringBuffer();
		int ai = a.length() - 1;
		int bi = b.length() - 1;
		int carry = 0;
		while (ai >= 0 || bi >= 0) {
			int numberA = ai >= 0 ? a.charAt(ai--) - '0' : 0;
			int numberB = bi >= 0 ? b.charAt(bi--) - '0' : 0;
			int sum = numberA + numberB + carry;
			sb.append(sum % 2);
			carry = sum / 2;
		}

		if (carry == 1)
			sb.append(carry);

		return sb.reverse().toString();
	}

	/**
	 * 
	 */
	public AddBinary() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AddBinary addBinary = new AddBinary();
		String a = "11";
		String b = "1";
		String result = addBinary.addBinary(a, b);

	}

}
